package com.itany.boot.service.impl;

import com.itany.boot.dao.UserDao;
import com.itany.boot.entity.User;
import com.itany.boot.exception.UserNotExistException;
import com.itany.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author shixiaojun@itany
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<User> findAll() {
        return userDao.selectAll();
    }

    @Override
    public void addUser(User user) {
        userDao.insertUser(user);
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public User findById(Integer id) {
        return userDao.selectById(id);
    }

    @Override
    public void modifyUser(User user) {
        userDao.updateUser(user);
    }

    @Override
    public void removeUser(Integer id) {
        userDao.deleteById(id);
    }

    @Override
    public User login(String username, String password) throws UserNotExistException {
        User user = userDao.selectByUsernameAndPassword(username, password);
        if(user == null){
            throw new UserNotExistException("用户名或密码错误");
        }
        return user;
    }
}
